﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Xml;

namespace SanctusSoftware.Music.ChordSheetEditor.Client
{
    public static class SettingsProcessor
    {

        public static string SettingsFilePath()
        {
            FileInfo assemblyFile = new FileInfo(Assembly.GetExecutingAssembly().Location);
            return Path.Combine(assemblyFile.DirectoryName, "Settings.xml");
        }

        public static bool SettingsFileExists()
        {
            return File.Exists(SettingsFilePath());
        }

        public static Settings GetSettings()
        {
            if (SettingsFileExists())
            {
                return GetSettings(SettingsFilePath());
            }
            else
            {
                return new Settings();
            }
        }

        public static Settings GetSettings(string fileName)
        {

            Settings s = new Settings();

            XmlDocument doc = new XmlDocument();
            doc.Load(fileName);

            s.Target = (ActionTarget)System.Enum.Parse(typeof(ActionTarget), doc["ChordSheetAddInForWord2007Settings"]["Target"].InnerText);
            s.MinimumChordLineMatchPercentage = int.Parse(doc["ChordSheetAddInForWord2007Settings"]["MinimumChordLineMatchPercentage"].InnerText);
            //s.LicenseKey = doc["ChordSheetAddInForWord2007Settings"]["LicenseKey"].InnerText;

            return s;

        }

        public static void SaveSettings(Settings settings)
        {
            SaveSettings(settings, SettingsFilePath());
        }

        public static void SaveSettings(Settings settings, string fileName)
        {
            XmlDocument doc = new XmlDocument();// Create the XML Declaration, and append it to XML document
            
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
            doc.AppendChild(dec);// Create the root element
            
            XmlElement root = doc.CreateElement("ChordSheetAddInForWord2007Settings");
            doc.AppendChild(root);

            XmlElement target = doc.CreateElement("Target");
            target.InnerText = settings.Target.ToString();
            root.AppendChild(target);

            XmlElement matchPercent = doc.CreateElement("MinimumChordLineMatchPercentage");
            matchPercent.InnerText = settings.MinimumChordLineMatchPercentage.ToString();
            root.AppendChild(matchPercent);

            //XmlElement licenseKey = doc.CreateElement("LicenseKey");
            //licenseKey.InnerText = settings.LicenseKey;
            //root.AppendChild(licenseKey);

            doc.Save(fileName);
        }

    }
}
